// 运行时配置

import { RequestConfig, RunTimeLayoutConfig, history } from '@umijs/max';
import { message, notification } from 'antd';
import Header from './layouts/header';
import { getUserAccount, getUserInfo } from './services/login';

// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
export async function getInitialState(): Promise<{
  getInitialUserInfo?: () => any;
  currentUser?: any;
  loading?: boolean;
  accountInfo?: any;
}> {
  let currentUser = undefined;
  let accountInfo = undefined;

  const getInitialUserInfo = async () => {
    const userInfo = await getUserInfo();
    const account = await getUserAccount();
    currentUser = userInfo;
    accountInfo = account;

    return {
      currentUser,
      accountInfo,
      getInitialUserInfo,
    };
  };
  if (location.pathname !== '/login') {
    await getInitialUserInfo();
  }
  // 如果不是登录页面，执行

  return {
    getInitialUserInfo,
    currentUser,
    loading: false,
    accountInfo,
  };
}

export const layout: RunTimeLayoutConfig = ({}) => {
  return {
    menu: {
      locale: false,
    },
    contentStyle: {
      padding: 0,
      minHeight: 'calc(100vh - 56px)',
    },
    logo: false,
    headerTitleRender: false,
    className: 'root-main',
    layout: 'mix',
    headerContentRender: () => {
      return <Header style={{ padding: 0 }} />;
    },
    menuDataRender: (menuData) => {
      if (history.location.pathname === '/') return menuData;
      const match = history.location.pathname.match(
        /^\/([^/]+)\/([^/]+)/,
      ) as any;
      return [
        menuData[0],
        ...menuData.filter((item) => item.path?.includes(match[1])),
      ];
    },
    onPageChange(location) {
      console.log('onPageChange', location?.pathname);
    },
    token: {
      sider: {
        colorMenuBackground: '#fff',
        colorTextMenuSelected: '#00bdff',
        colorTextMenuItemHover: '#00bdff',
        colorBgMenuItemSelected: '#f4fbff',
        colorBgMenuItemHover: '#f4fbff',
        colorBgMenuItemActive: '#fff',
      },

      pageContainer: {
        colorBgPageContainer: '#f7f9ff',
      },
    },
  };
};

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
//请求配置
export const request: RequestConfig = {
  timeout: 1200000,
  baseURL:
    process.env.NODE_ENV === 'development' ? '/api' : process.env.BASE_URL,
  // other axios options you want
  errorConfig: {
    errorHandler(error: any) {
      const { response } = error;
      if (response && response.status > 500) {
        message.error('请求错误：服务器故障，请稍后再试');
      }
    },
    errorThrower() {},
  },
  // 请求拦截
  requestInterceptors: [
    (config: any) => {
      // console.log('getToken()', getToken());
      // if (getToken()) {
      //   config.headers['token'] = getToken();
      // }
      if (!['/common/login/form'].includes(config.url)) {
        config.headers['Content-Type'] = 'application/json';
      }
      return config;
    },
    (error: any) => {
      return error;
    },
  ],
  // 响应拦截
  responseInterceptors: [
    (response: any) => {
      const code = response.status;
      console.log('response=====>', response);
      if (code < 200 || code > 300) {
        notification.error({
          message: response.data.resultMessage,
        });
        return Promise.reject('error');
      }
      if (response.data.resultCode === 'user.need_login') {
        history.push('/login');
        return response;
      }
      return response.data;
    },
  ],
};
